package com.sky.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * @Author 2230823078_淡嘉浩
 * @Date 2025/3/7 下午11:06
 * Please don't copy!
 */
@RestController
@RequestMapping("/admin/dish")
@Api(tags = "菜品相关接口")
public class DishController {

    private static final Logger log = LoggerFactory.getLogger(DishController.class);
    @Autowired
    private DishService dishService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping
    public Result save(@RequestBody DishDTO dishDTO){

        dishService.saveWithFlavor(dishDTO);
        cleanCache("dish:"+dishDTO.getCategoryId());
        return Result.success();
    }

    @GetMapping("/page")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO){
        log.info("分页查询：{}", dishPageQueryDTO);
        PageResult pageResult = dishService.pageQuery(dishPageQueryDTO);

        return Result.success(pageResult);
    }
    @DeleteMapping
    public Result delete(@RequestParam("ids") Long[] ids){
        log.info("批量删除菜品：{}", ids);
        dishService.deleteBatch(ids);
        cleanCache("dish:*");
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result<DishVO> getById(@PathVariable Long id){

        DishVO dishVO = dishService.getById(id);

        return Result.success(dishVO);
    }
    //修改菜品
    @PutMapping
    @ApiOperation("修改菜品")
    public Result update(@RequestBody DishDTO dishDTO){
        log.info("修改菜品；{}",dishDTO);
        dishService.updateWithFlavor(dishDTO);
        cleanCache("dish:*");
        return Result.success();
    }
    @PostMapping("/status/{status}")
    public Result startOrStop(@PathVariable Integer status, Long id){
        log.info("起售停售：{}",id);
        dishService.startOrStop(status,id);
        cleanCache("dish:*");
        return Result.success();
    }
    @GetMapping("/list")
    public Result<List<Dish>> list(@RequestParam("categoryId")Long categoryId){

        List<Dish> dishes = dishService.queryById(categoryId);
        return Result.success(dishes);

    }

    //清理缓存数据
    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
